# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
from openerp.tools.translate import _


class purchase_order_group(osv.osv_memory):
    _name = "purchase.order.group"
    _inherit = 'purchase.order.group'
    _description = "Purchase Order Merge"

    def fields_view_get(self, cr, uid, view_id=None, view_type='form',
                        context=None, toolbar=False, submenu=False):

        if context is None:
            context = {}
        res = super(purchase_order_group, self).fields_view_get(
            cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        if context.get('active_model', '') == 'purchase.order' and len(context['active_ids']) >= 1:
            for purchase_obj in self.pool.get('purchase.order').browse(
                    cr, uid, context.get("active_ids"), context=context):
                if self.pool.get('stock.picking').search(cr, uid, [('po_id', '=', purchase_obj.id)], context=context):
                    raise osv.except_osv(
                        u'错误', u"%s 采购单已经有入库单存在，不能进行合并操作!" % (purchase_obj.name))
                if purchase_obj.voucher_id:
                    raise osv.except_osv(
                        u'错误', u"%s采购单已经申请过预付款，不能进行合并操作!" % (purchase_obj.name))

                if purchase_obj.invoice_ids:
                    raise osv.except_osv(
                        u'错误', u"%s采购单已经有发票，不能进行合并操作!" % (purchase_obj.name))
        return res

    def merge_orders(self, cr, uid, ids, context=None):
        # 合并采购单
        group = self.browse(cr, uid, ids, context=context)
        list_purchase_order = {}
        gropu_purchase_order_models = self.pool.get('purchase.order').browse(
            cr, uid, [int(group.all_purchase_to_merge)], context=context)
        order_approved = False
        if gropu_purchase_order_models.state == 'approved':
            order_approved = True
        for purchase_obj in self.pool.get('purchase.order').browse(
                cr, uid, context.get("active_ids"), context=context):
            if purchase_obj.state == 'approved':
                self.pool.get('purchase.order').button_modify_order(
                    cr, uid, [purchase_obj.id], context=context)
        sale_order_list = []
        sale_order_list.append(gropu_purchase_order_models.so_code_list)
        # 记录要合并到的订单 中的数据 并删除v原数据
        nochahge_purchase_order_line_dict = {}
        if gropu_purchase_order_models:
            for gropu_purchase_order_model in gropu_purchase_order_models.order_line:
                if gropu_purchase_order_model.product_id.id in list_purchase_order:
                    list_purchase_order.get(gropu_purchase_order_model.product_id.id)[0].update(
                        {'product_qty': list_purchase_order.get(gropu_purchase_order_model.product_id.id)[0].get('product_qty') + gropu_purchase_order_model.product_qty})
                else:
                    list_purchase_order.update(
                        {gropu_purchase_order_model.product_id.id: gropu_purchase_order_model.read()})
                nochahge_purchase_order_line_dict.update({gropu_purchase_order_model.product_id.id: gropu_purchase_order_model.id})
                # self.pool.get('purchase.order.line').unlink(
                #     cr, uid, [gropu_purchase_order_model.id], context=context)   # 需求更新 删除订单行会返回 采购需求会返回 采购助手 所以改变 逻辑
        # 提取所有的要合并的信息（1，要合并到的订单的信息和 被合并的信息进行合并 2.取消被合并的订单）
        for gropu_purchase_order in self.pool.get('purchase.order').browse(cr, uid, list(set(context.get('active_ids')) - set([int(group.all_purchase_to_merge)])), context=context):
            sale_order_list.append(gropu_purchase_order.so_code_list)
            for order_line in gropu_purchase_order.order_line:
                if order_line.product_id.id in list_purchase_order:
                    list_purchase_order.get(order_line.product_id.id)[0].update(
                        {'product_qty': list_purchase_order.get(order_line.product_id.id)[0].get('product_qty') + order_line.product_qty})
                else:
                    list_purchase_order.update(
                        {order_line.product_id.id: order_line.read()})
            self.pool.get('purchase.order').action_cancel(
                cr, uid, [gropu_purchase_order.id], context=context)
        # 把提取到的信息 写入到要合并的订单中
        for order_line_val in list_purchase_order.values():
            del order_line_val[0]['id'], order_line_val[0][
                'write_uid'], order_line_val[0]['create_date'], order_line_val[0]['create_uid'], order_line_val[0][
                '__last_update'], order_line_val[0]['order_id'], order_line_val[0]['write_date']
            order_line_val[0].update(
                {'order_id': int(group.all_purchase_to_merge), 'product_uom': order_line_val[0].get('product_uom')[0],
                 'partner_id': order_line_val[0].get('partner_id')[0], 'company_id': order_line_val[0].get('company_id')[0], 'product_id': order_line_val[0].get('product_id')[0]})
            if order_line_val[0].get('product_id') in nochahge_purchase_order_line_dict:
                # 删除已有订单行 会牵涉到采购助手生成采购需求 量的计算 所以要覆盖原有的记录而不能 删除采购单行.
                order_line_val[0].update({'prod_spec': False})
                self.pool.get('purchase.order.line').write(
                    cr, uid, nochahge_purchase_order_line_dict.get(order_line_val[0].get('product_id')), order_line_val[0], context=context)
            else:
                self.pool.get('purchase.order.line').create(
                    cr, uid, order_line_val[0], context=context)
        # 并把 各个订单中的关联的销售订单的 单号 进行合并，到 合并到的订单中
        gropu_purchase_order_models.write(
            {'so_code_list': '、'.join(map(str, sale_order_list))})
        if order_approved:
            # 合并到确认后的采购单 合并后要进行确认
            self.pool.get('purchase.order').signal_workflow(
                cr, uid, [gropu_purchase_order_models.id], 'purchase_confirm')
            # 操作成功后显示 合并成功的那个的采购单（并且取消合并过的采购单）
        return {
            'domain': "[('id','=', " + group.all_purchase_to_merge + ")]",
            'name': _('Purchase Orders'),
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'purchase.order',
            'res_id': int(group.all_purchase_to_merge),
            'type': 'ir.actions.act_window',
        }

    def _get_select_order(self, cr, uid, ids, context=None):
        # 得到所选的采购单的单的相关信息
        purchase_order_objs = self.pool.get('purchase.order').browse(
            cr, uid, context.get("active_ids"), context=context)
        return [(purchase_order_obj.id, purchase_order_obj.name) for purchase_order_obj in purchase_order_objs]

    def _get_messege(self, cr, uid, context=None):
        # 调用这个方法进行所选数据的初步的判断
        partner_id, purchase_order_id = [], []
        for purchase_order_obj in self.pool.get('purchase.order').browse(
                cr, uid, context.get("active_ids"), context=context):
            partner_id.append(purchase_order_obj.partner_id.id)
            purchase_order_id.append(purchase_order_obj.id)
            if purchase_order_obj.state == 'cancel':
                return 2
        if len(set(partner_id)) > 1:
            return 1
        if len(purchase_order_id) <= 1:
            return 3
        return 4
    _columns = {
        'all_purchase_to_merge': fields.selection('_get_select_order', string='合并到这个询价单中', required=True),
        'continue_is_ok': fields.selection([(1, u'不是同一个供应商'), (2, u'有取消的采购单'), (3, u'只选择一个采购单'), (4, '正常')], u'可以继续操作')
    }
    _defaults = {
        'continue_is_ok': _get_messege,
    }


# class purchase_order_line(osv.osv):
#     _name = 'purchase.order.line'
#     _inherit = 'purchase.order.line'

#     def write(self, cr, uid, ids, vals, context=None):
#         for purchase in self.browse(cr, uid, ids, context=context):
#             if (vals.get('incomed_qty') and vals.get('product_qty') and vals.get('product_qty') < vals.get('incomed_qty')) or (purchase.product_qty < purchase.incomed_qty):
#                 product_obj = self.pool.get('product.product').browse(
#                     cr, uid, vals.get('product_id'), context=context)
#                 raise osv.except_osv(u'错误', u"%s已入库%s，不能减少数量小于入库数!" %
#                                      (product_obj.name, vals.get('incomed_qty')))
#             super(purchase_order_line, self).write(
#                 cr, uid, ids, vals, context=context)
#         return True
